package com.fzfnn.scrapbook.controller;

import com.fzfnn.scrapbook.entity.Message;
import com.fzfnn.scrapbook.entity.User;
import com.fzfnn.scrapbook.service.MessageService;
import com.fzfnn.scrapbook.service.UserService;
import com.fzfnn.scrapbook.util.R;
import com.fzfnn.scrapbook.vo.PrivateChatUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ChatWebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @MessageMapping("/chat")  // 客户端发送到 /app/chat
    public void handleChat(@Payload Message message) {

        // 根据 senderId 查询用户名
        User sender = userService.selectUserByid(message.getSenderId());
        String senderName = sender != null ? sender.getUsername() : "未知用户";
        // 保存消息
        messageService.saveMessage(message);
        message.setSenderName(senderName);

        // 推送给接收者（queue 点对点）
        messagingTemplate.convertAndSendToUser(
                message.getReceiverId().toString(), // userId 作为 user-specific destination
                "/queue/messages",
                message
        );
    }



}
